/**
 * 
 */
package com.nashuju.app.api;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nashuju.web.common.Config;
import com.nashuju.web.entity.sw.SMessage;
import cn.jpush.api.JPushClient;
import cn.jpush.api.common.APIConnectionException;
import cn.jpush.api.common.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

/**
 * @author xiaoren
 *
 */
public class JPush {
	
	 	protected static final Logger LOG = LoggerFactory.getLogger(JPush.class);
	 
	    // demo App defined in resources/jpush-api.conf 
		private static final String appKey =Config.appKey;
		private static final String masterSecret = Config.masterSecret;
		public static final String TITLE = "Test from API example";
	    public static final String ALERT = "Test from API Example - alert";
	    public static final String MSG_CONTENT = "Test from API Example - msgContent";
	    public static final String REGISTRATION_ID = "0900e8d85ef";
	    public static final String TAG = "tag_api";
		public static final boolean APNS = false;
		static JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);

		public static boolean alertByRegistrationId(String registrationId , String alertMessage, String message) {

        // For push, all you need do is to build PushPayload object.
       // PushPayload payload = buildPushObject_all_registrationId_alert(registrationId ,  message);
        PushPayload payload =  buildPushObject_android_and_ios(registrationId ,  alertMessage, message);

       
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            LOG.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            LOG.error("Should review the error, and fix the request", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            return false;
        }
        return true;
	}
	
	
	public static PushPayload buildPushObject_all_all_alert() {
	    return PushPayload.alertAll(ALERT);
	}
	
	
	public static PushPayload buildPushObject_all_registrationId_alert(String registrationId , String message) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.alert(message))
                .build();
    }
    
    public static PushPayload buildPushObject_android_tag_alertWithTitle() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.android(ALERT, TITLE, null))
                .build();
    }
    public static PushPayload buildPushObject_android_and_ios(String registrationId , String alert , String MSG_CONTENT) {
    	return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId))
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .build())
                .build();
    }
    
    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and("tag1", "tag_all"))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(ALERT)
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                 .setMessage(Message.content(MSG_CONTENT))
                 .setOptions(Options.newBuilder()
                         .setApnsProduction(true)
                         .build())
                 .build();
    }
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }

    public static boolean alertByRegistrationId(String registrationId, String alertMessage,
			Map<String, Object> message) {

		PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(REGISTRATION_ID, alertMessage,
				message);

		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("Got result - " + result);

		} catch (APIConnectionException e) {
			LOG.error("Connection error, should retry later", e);

		} catch (APIRequestException e) {
			LOG.error("Should review the error, and fix the request", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			return false;
		}
		return true;
	}

	public static PushPayload buildPushObject_all_all_alert(String ale) {
		return PushPayload.alertAll(ale);
	}

	/**
	 * 消息推送
	 * 
	 * @param ALERT
	 *            用户使用机器编号
	 * @param msg
	 *            消息内容
	 * @return PushPayload
	 */
	public static PushPayload buildPushObject_all_alias_alert(String ALERT, String msg) {
		return PushPayload.newBuilder().setPlatform(Platform.all())
				.setAudience(Audience.registrationId(REGISTRATION_ID)).setNotification(Notification.alert(msg)).build();
	}

	public static PushPayload buildPushObject_all_alias_alert() {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias("alias1"))
				.setNotification(Notification.alert(ALERT)).build();
	}

	/**
	 * 
	 * @param registrationId
	 *            设备标识
	 * @param alert
	 *            编号
	 * @param MSG_CONTENT
	 *            消息内容
	 * @param cont
	 *            统计数字
	 * @return
	 */
	public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String registrationId, String alert,
			Map<String, Object> MSG_CONTENT) {
		if (registrationId.equals(REGISTRATION_ID)) {
			registrationId = REGISTRATION_ID;
		}
		int cont = (int) MSG_CONTENT.get("cont");
		if (cont != 0) {
			return PushPayload.newBuilder().setPlatform(Platform.ios())
					.setAudience(Audience.registrationId(registrationId))
					.setNotification(Notification.newBuilder()
							.addPlatformNotification(IosNotification.newBuilder().setAlert(alert).setSound("default")
									.setBadge(cont).addExtra("msg", MSG_CONTENT.get("id").toString()).build())
							.build())
					.setOptions(Options.newBuilder().setApnsProduction(APNS).build()).build();
		} else {
			return PushPayload.newBuilder().setPlatform(Platform.ios())
					.setAudience(Audience.registrationId(registrationId))
					.setNotification(Notification.newBuilder()
							.addPlatformNotification(IosNotification.newBuilder().setAlert(alert).setSound("default")
									.addExtra("msg", MSG_CONTENT.get("id").toString()).build())
							.build())
					.setOptions(Options.newBuilder().setApnsProduction(APNS).build()).build();
		}

	}

	public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(String registrationId, String alert,
			String MSG_CONTENT, int cont) {
		return PushPayload.newBuilder().setPlatform(Platform.android_ios())
				.setAudience(Audience.newBuilder().addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
						.addAudienceTarget(AudienceTarget.alias("alias1", "alias2")).build())
				.setMessage(Message.newBuilder().setMsgContent(MSG_CONTENT).addExtra("from", "JPush").build()).build();
	}
	public static boolean alertByRegistrationIdForiOS(String registrationId , String alertMessage ,int taskId) {

        PushPayload payload =  buildPushObject_android_and_ios_foriOS(registrationId ,  alertMessage, taskId);

       
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            LOG.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            LOG.error("Should review the error, and fix the request", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            return false;
        }
        return true;
	}
	public static PushPayload buildPushObject_android_and_ios_foriOS(String registrationId , String alert , int taskId) {
    	
		
		
		return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .setSound("happy")
                                .addExtra("id", ""+taskId)
                                .build())
                        .build())
                		
                .setOptions(Options.newBuilder().setApnsProduction(false).build()).build();
               
    }
	

	public static void addAlertInDB(String message , int userId){
		
		Config.cSql.excutSql("insert INTO s_message ( message, user_id , send_type, send_tag) VALUES ( "+message+","+userId+" ,'Jpush','alert')", new SMessage());
		
	}
	
	public static void main(String[] args) {

		alertByRegistrationIdForiOS("1114a89792a9966d46c","aaaa",4);
		
	}
    
    
}
